﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Repository;
using Estimate.Common.Entity;
using Estimate.Common.Estimate;
using Estimate.Common.Estimate.EstimateValue;
using Newtonsoft.Json;

namespace Estimate.Reports
{
    /// <summary>
    /// 气温图表数据
    /// </summary>
   public  class TempDiagramReport
    {
        ExecutionStatus exeStatus;//程序执行状态
        protected string connectionString;

        public TempDiagramReport(string ConnectionString,string tid)
        {
            connectionString = ConnectionString;

            if (tid != "") 
                exeStatus = new ExecutionStatus(tid);
        }

        //public string GetReportDataString(Dictionary<string, string> tables, DateTime dt, ForeSpanType span, string station, ForeSendpointType sendpoint)
        //{
        //    if (exeStatus != null) exeStatus.SetMessage("GetReportDataString", "正在获得计算结果");

        //    Dictionary<string, DiagramData> reportData = new Dictionary<string, DiagramData>();
        //    DiagramData maxtemp = new DiagramData();
        //    DiagramData mintemp = new DiagramData();
        //    reportData.Add("maxt", maxtemp);
        //    reportData.Add("mint", mintemp);

        //    List<DateTime> days = new List<DateTime>();
        //    List<ForeSpanType> spans = new List<ForeSpanType>();

        //    for (int i = 0; i < DeviationDays(span); i++)
        //    {
        //        maxtemp.coord_x.Add(dt.AddDays(i).ToString("yyyy-MM-dd"));
        //        mintemp.coord_x.Add(dt.AddDays(i).ToString("yyyy-MM-dd"));
        //        days.Add(dt.AddDays(i));

        //        string spanstr = string.Format("FD{0}_{1}", (24 * i).ToString().PadLeft(2, '0'), (24 * (i + 1)).ToString());
        //        spans.Add((ForeSpanType)Enum.Parse(typeof(ForeSpanType), spanstr));
        //    }

        //    List<float> maxtempreal = GetRealTempData(days, span, sendpoint, ForeFactorType.maxt, station);
        //    List<float> mintempreal = GetRealTempData(days, span, sendpoint, ForeFactorType.mint, station);
        //    maxtemp.coord_y.Add(new Dictionary<string, List<float>>() { { "real", maxtempreal } });
        //    mintemp.coord_y.Add(new Dictionary<string, List<float>>() { { "real", mintempreal } });

        //    foreach (KeyValuePair<string,string> pair in tables)
        //    {
        //        List<float> maxtempfore = GetForeTempData(dt, spans.ToArray(), sendpoint, ForeFactorType.maxt, station, pair.Value);
        //        List<float> mintempfore = GetForeTempData(dt, spans.ToArray(), sendpoint, ForeFactorType.mint, station, pair.Value);
        //        maxtemp.coord_y.Add(new Dictionary<string, List<float>>() { { pair.Key, maxtempfore } });
        //        mintemp.coord_y.Add(new Dictionary<string, List<float>>() { { pair.Key, mintempfore } });
        //    }

        //    if (exeStatus != null)
        //    {
        //        exeStatus.DeleteMessage("GetReportDataString");
        //        exeStatus.SetMessage(true, "ExecutionEnd", "程序执行完毕");

        //    }

        //    return JsonConvert.SerializeObject(reportData);

        //}
       
       public string GetReportDataString(Dictionary<string, string> tables, DateTime dt, string span, string station, ForeSendpointType sendpoint)
        {
            if (exeStatus != null) exeStatus.SetMessage("GetReportDataString", "正在获得计算结果");

            Dictionary<string, List<Dictionary<string, object>>> reportData = new Dictionary<string, List<Dictionary<string, object>>>();
            
            reportData.Add("maxt",  new List<Dictionary<string, object>>());
            reportData.Add("mint",  new List<Dictionary<string, object>>());

          
            for (int i = 0; i < DeviationDays(span); i++)
            {
                Dictionary<string, object> maxtemp = new Dictionary<string, object>();
                Dictionary<string, object> mintemp = new Dictionary<string, object>();
                reportData["maxt"].Add(maxtemp);
                reportData["mint"].Add(mintemp);

                maxtemp.Add("date", dt.AddDays(i).ToString("yyyy-MM-dd"));
                mintemp.Add("date",dt.AddDays(i).ToString("yyyy-MM-dd"));
               
                string spanstr = string.Format("FD{0}_{1}", (24 * i).ToString().PadLeft(2, '0'), (24 * (i + 1)).ToString());
                ForeSpanType foreSpan = (ForeSpanType)Enum.Parse(typeof(ForeSpanType), spanstr);

                 maxtemp.Add("real",GetRealTempData(dt.AddDays(i), foreSpan, sendpoint, ForeFactorType.maxt, station));
                 mintemp.Add("real",GetRealTempData(dt.AddDays(i), foreSpan, sendpoint, ForeFactorType.mint, station));

                 foreach (KeyValuePair<string, string> pair in tables)
                 {
                     maxtemp.Add(pair.Key, GetForeTempData(dt, foreSpan, sendpoint, ForeFactorType.maxt, station, pair.Value));
                     mintemp.Add(pair.Key, GetForeTempData(dt, foreSpan, sendpoint, ForeFactorType.mint, station, pair.Value));
                     
                 }

            }

            if (exeStatus != null)
            {
                exeStatus.DeleteMessage("GetReportDataString");
                exeStatus.SetMessage(true, "ExecutionEnd", "程序执行完毕");

            }

            DiagramData result = new DiagramData();
            result.result = reportData;
            return JsonConvert.SerializeObject(result).Replace("99.9","null");

        }

       private float GetRealTempData(DateTime date, ForeSpanType span, ForeSendpointType sendpoint, ForeFactorType type, string station)
       {
           ForeRealLinker RelatedLinker = new ForeRealLinker();
           TempRealRepository RelatedTempRepository = TempRealRepositoryFactory.AutoStationTempRealRepository(connectionString);
           SendpointToClock parser = new SendpointToClock();
           ForeClockType[] clocks = parser.GetClockArrayWithSendPointArray(new ForeSendpointType[] { sendpoint });


           TempForeRealCompare comparer = RelatedLinker.GetForeRelatedTempCondition(date, span, clocks[0], type);
           string real = RelatedTempRepository.GetValue(comparer.RealDate, comparer.TempType);

           return SelectDataByStation(real, station);

       }

       private float GetForeTempData(DateTime dt, ForeSpanType span, ForeSendpointType sendpoint, ForeFactorType type, string station, string table)
       {

           ForeSendpointType[] sendpoints = new ForeSendpointType[] { sendpoint };
           SendpointToClock parser = new SendpointToClock();
           ForeClockType[] clocks = parser.GetClockArrayWithSendPointArray(new ForeSendpointType[] { sendpoint });

           ForeRepository repository = ForeRepositoryFactory.ForeDataRepository(connectionString, table);// new ForeRepository(connectionString, table);

           ForeEntity[] entitys = repository.InquerySemiWithDateRange(dt, dt, clocks, span, sendpoints, type, ForeSemiType.Auto, false);
           if (entitys.Length > 0)
               return SelectDataByStation(entitys[0].Value, station);

           return 99.9f;
       }

        private float SelectDataByStation(string value, string station)
       {
           foreach (string s in value.Split(new char[] { '|' }))
           {
               string[] ss = s.Split(new char[] { ';' });
               if (ss.Length >= 2 && ss[0] == station)
                   return float.Parse(string.Format("{0:N1}", ss[1]));

           }
           return 99.9f;
       }

       private int DeviationDays(string span)
       {
           string strSpan = span.ToString().Replace("FD", "");
           string[] hours = strSpan.Split('_');
           //int start = Convert.ToInt32(hours[0]);
           int end = Convert.ToInt32(span);


           int days = end / 24;
           days = days == 0 ? 1 : days;
           return days;
       }

    }

    public class DiagramData
    {
        public string success = true.ToString();
        public string msg = "";
        public Dictionary<string, List<Dictionary<string, object>>> result;

        public DiagramData()
        {
           
        }
    }
}
